package com.wrupple.muba.catalogs.server.integration.locator.impl;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.wrupple.muba.catalogs.client.activity.CatalogActivity;
import com.wrupple.muba.catalogs.server.integration.locator.CatalogDataServiceLocator;
import com.wrupple.muba.catalogs.server.process.impl.CatalogRequestHandlingProcessImpl;
import com.wrupple.vegetate.domain.exceptions.IntegrationLayerException;
import com.wrupple.vegetate.server.VegetateServiceLocator;
import com.wrupple.vegetate.server.integration.HttpServletRequestHandler;
import com.wrupple.vegetate.server.integration.impl.AbstractVegetateService;
import com.wrupple.vegetate.server.integration.impl.ProcessDelegatingRequestHandler;

public class CatalogDataServiceLocatorImpl extends AbstractVegetateService implements CatalogDataServiceLocator {

	
	
	private EventBus bus;
	protected Provider<? extends CatalogRequestHandlingProcessImpl> delegateProvider;
	protected VegetateServiceLocator childServiceLocator;
	
	@Inject
	public CatalogDataServiceLocatorImpl(EventBus bus,
			Provider<CatalogRequestHandlingProcessImpl> delegateProvider) {
		super();
		this.bus = bus;
		this.delegateProvider = delegateProvider;
	}

	@Override
	public Collection<VegetateServiceLocator> getChildren() {
		return null;
	}
	
	@Override
	public void serve(HttpServletRequest req, HttpServletResponse resp,
			Map<String, String> pathParameters) throws IOException,
			IntegrationLayerException {
		if(super.requestHandler==null){
			super.requestHandler=getHandlerForToken(null);
		}
		super.serve(req, resp, pathParameters);
	}

	@Override
	protected HttpServletRequestHandler getHandlerForToken(String tokenName) {
		CatalogRequestHandlingProcessImpl delegate=delegateProvider.get();
		return new ProcessDelegatingRequestHandler(bus, delegate, childServiceLocator);
	}
	

	@Override
	public String getName() {
		return CatalogActivity.CATALOG_ENTRY_PARAMETER;
	}


}
